﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;

namespace HttpListenerApplication
{
    public partial class frmWelcome : Form
    {
        public frmWelcome()
        {
            InitializeComponent();
        }

        private string softName = "智能加密狗";

        Boolean isClose = false;

        // https://blog.csdn.net/heyangyi_19940703/article/details/51201224

        private void addListener()
        {
            HttpListener listerner = new HttpListener();

            try
            {
                listerner.AuthenticationSchemes = AuthenticationSchemes.Anonymous;//指定身份验证 Anonymous匿名访问
                listerner.Prefixes.Add("http://127.0.0.1:1500/Service/");
                listerner.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(softName + "启动失败\r\n" + ex.Message);
                Application.Exit();
                Application.ExitThread();
            }

            Console.WriteLine("服务器启动成功.......");
            this.ntfListener.ShowBalloonTip(5000, softName, "启动成功，我很安静哦。", ToolTipIcon.None);

            //线程池
            int minThreadNum;
            int portThreadNum;
            int maxThreadNum;
            ThreadPool.GetMaxThreads(out maxThreadNum, out portThreadNum);
            ThreadPool.GetMinThreads(out minThreadNum, out portThreadNum);
            Console.WriteLine("最大线程数：{0}", maxThreadNum);
            Console.WriteLine("最小空闲线程数：{0}", minThreadNum);
            //ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc1), x);

            Console.WriteLine("\n\n等待客户连接中。。。。");
            while (!isClose)
            {
                //等待请求连接
                //没有请求则GetContext处于阻塞状态
                HttpListenerContext ctx = listerner.GetContext();

                ThreadPool.QueueUserWorkItem(new WaitCallback(TaskProc), ctx);
            }
            //listerner.Stop();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Top = -1000;
            this.Left = -1000;
            this.Visible = false;

            this.ntfListener.Text = softName;

            Thread t = new Thread(new ThreadStart(addListener));
            t.IsBackground = true;
            t.Start();
        }

        static void TaskProc(object o)
        {
            HttpListenerContext ctx = (HttpListenerContext)o;

            ctx.Response.StatusCode = 200;//设置返回给客服端http状态代码
            ctx.Response.ContentType = "text/html;charset=utf-8";

            //string json;

            //using (Stream inputStream = ctx.Request.InputStream)
            //using (StreamReader reader22 = new StreamReader(inputStream))
            //{
            //    json = reader22.ReadToEnd();
            //}

            //接收Get参数
            string type = ctx.Request.QueryString["type"];
            string left = ctx.Request.QueryString["l"];
            string right = ctx.Request.QueryString["r"];
            //string filename = Path.GetFileName(ctx.Request.RawUrl);
            // string userName = HttpUtility.ParseQueryString(filename).Get("userName");//避免中文乱码
            //进行处理
            // Console.WriteLine("收到数据:" + userName);

            //接收POST参数
            Stream stream = ctx.Request.InputStream;
            System.IO.StreamReader reader = new System.IO.StreamReader(stream, Encoding.UTF8);
            String body = reader.ReadToEnd();
            //Console.WriteLine("收到POST数据:" + HttpUtility.UrlDecode(body));
            //Console.WriteLine("解析:" + HttpUtility.ParseQueryString(body).Get("userName"));

            //使用Writer输出http响应代码,UTF8格式
            using (StreamWriter writer = new StreamWriter(ctx.Response.OutputStream, Encoding.UTF8))
            {
                string uuid = "";
                string resCode = "0";
                try
                {
                    if (type == "l")    // login
                    {
                        uuid = DevicesHelper.getPCUUID(left, right);
                    }
                    else if (type == "r")   // register
                    {
                        uuid = DevicesHelper.getRegterInfo();
                    }
                }
                catch (Exception)
                {
                    resCode = "1";
                }
                string f = resCode + "," + uuid;

                writer.Write(f);
                // writer.Write("数据是userId={0},userName={1}", userId, userName);
                writer.Close();
                ctx.Response.Close();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            isClose = true;
        }
    }
}
